package com.pig4cloud.pig.duorou.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.duorou.entity.DuorouGreenhouseDeviceEntity;
import com.pig4cloud.pig.duorou.service.DuorouGreenhouseDeviceService;
import com.pig4cloud.pig.iot.constant.IotDeviceStatusConstant;
import com.pig4cloud.pig.iot.entity.IotDeviceEntity;
import com.pig4cloud.pig.iot.service.IotDeviceService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 多肉-关系表大棚和设备之间1-n
 *
 * @author lty
 * @date 2024-11-05 20:24:38
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/duorouGreenhouseDevice" )
@Tag(description = "duorouGreenhouseDevice" , name = "多肉-关系表大棚和设备之间1-n管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class DuorouGreenhouseDeviceController {

    private final  DuorouGreenhouseDeviceService duorouGreenhouseDeviceService;

	private final IotDeviceService iotDeviceService;


	/**
     * 根据大鹏ID获取设备列表
     * @param page 分页对象
     * @param duorouGreenhouseDevice 关系表大棚和设备之间1-n
	 * @param iotDevice
     * @return
     */
    @Operation(summary = "根据大鹏ID获取设备列表" , description = "分页查询" )
    @GetMapping("/getDeviceListByHouseID" )
    @PreAuthorize("@pms.hasPermission('duorou_duorouGreenhouseDevice_view')" )
    public R getDeviceListByHouseID(@ParameterObject Page page,
										   @ParameterObject DuorouGreenhouseDeviceEntity duorouGreenhouseDevice,
										   @ParameterObject IotDeviceEntity iotDevice) {
		List<Long> deviceIDListByGreenhouseId = duorouGreenhouseDeviceService.getDeviceIDListByGreenhouseId(duorouGreenhouseDevice.getGreenhouseId());
		List<IotDeviceEntity> reList=new LinkedList<>();
		if(deviceIDListByGreenhouseId.size()<=0){
			return R.ok(reList);
		}
		LambdaQueryWrapper<IotDeviceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.like(StrUtil.isNotBlank(iotDevice.getDeviceName()),IotDeviceEntity::getDeviceName,iotDevice.getDeviceName());
		wrapper.eq(StrUtil.isNotBlank(iotDevice.getDeviceCode()),IotDeviceEntity::getDeviceCode,iotDevice.getDeviceCode());
		wrapper.eq(StrUtil.isNotBlank(iotDevice.getDeviceOnlineStatus()),IotDeviceEntity::getDeviceOnlineStatus,iotDevice.getDeviceOnlineStatus());
		wrapper.like(StrUtil.isNotBlank(iotDevice.getDeviceAddress()),IotDeviceEntity::getDeviceAddress,iotDevice.getDeviceAddress());
		wrapper.eq(Objects.nonNull(iotDevice.getDeviceCategoryId()),IotDeviceEntity::getDeviceCategoryId,iotDevice.getDeviceCategoryId());
		wrapper.eq(StrUtil.isNotBlank(iotDevice.getDeviceBindStatus()),IotDeviceEntity::getDeviceBindStatus,iotDevice.getDeviceBindStatus());
		wrapper.in(deviceIDListByGreenhouseId.size()>0,IotDeviceEntity::getId,deviceIDListByGreenhouseId);
		reList = iotDeviceService.list(wrapper);
		return R.ok(reList);
    }


    /**
     * 通过id查询关系表大棚和设备之间1-n
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('duorou_duorouGreenhouseDevice_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(duorouGreenhouseDeviceService.getById(id));
    }

    /**
     * 新增关系表大棚和设备之间1-n
     * @param duorouGreenhouseDeviceEntityList 关系表大棚和设备之间1-n
     * @return R
     */
    @Operation(summary = "新增关系表大棚和设备之间1-n" , description = "新增关系表大棚和设备之间1-n" )
    @SysLog("新增关系表大棚和设备之间1-n" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('duorou_duorouGreenhouseDevice_add')" )
	@Transactional(isolation = Isolation.REPEATABLE_READ)
    public R save(@RequestBody List<DuorouGreenhouseDeviceEntity> duorouGreenhouseDeviceEntityList) {
		//todo 一般这里要座一层检查判断 设备有没有被绑定过 已绑定过就弹出体术 由于前端做了这个类似操作 这里先不新增代码检测
		// 使用 Stream API 提取 deviceId 并组成 List<Long>
		List<Long> deviceIdList = duorouGreenhouseDeviceEntityList.stream()
				.map(DuorouGreenhouseDeviceEntity::getDeviceId)
				.toList();

		boolean b = duorouGreenhouseDeviceService.saveBatch(duorouGreenhouseDeviceEntityList);
		//设置绑定状态
		LambdaUpdateWrapper<IotDeviceEntity> updateWrapper=new LambdaUpdateWrapper<>();
		updateWrapper.set(IotDeviceEntity::getDeviceBindStatus, IotDeviceStatusConstant.DEVICE_BINDED_STATUS);
		updateWrapper.in(IotDeviceEntity::getId,deviceIdList);
		boolean update = iotDeviceService.update(updateWrapper);
		return R.ok((b && update));
    }

    /**
     * 修改关系表大棚和设备之间1-n
     * @param duorouGreenhouseDevice 关系表大棚和设备之间1-n
     * @return R
     */
    @Operation(summary = "修改关系表大棚和设备之间1-n" , description = "修改关系表大棚和设备之间1-n" )
    @SysLog("修改关系表大棚和设备之间1-n" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('duorou_duorouGreenhouseDevice_edit')" )
    public R updateById(@RequestBody DuorouGreenhouseDeviceEntity duorouGreenhouseDevice) {
        return R.ok(duorouGreenhouseDeviceService.updateById(duorouGreenhouseDevice));
    }



    /**
     * 通过id删除关系表大棚和设备之间1-n
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除关系表大棚和设备之间1-n" , description = "通过id删除关系表大棚和设备之间1-n" )
    @SysLog("通过id删除关系表大棚和设备之间1-n" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('duorou_duorouGreenhouseDevice_del')" )
	@Transactional(isolation = Isolation.REPEATABLE_READ)
    public R removeById(@RequestBody List<DuorouGreenhouseDeviceEntity> duorouGreenhouseDeviceEntityList) { //Long[] ids

		if(duorouGreenhouseDeviceEntityList.size()<=0){
			return R.failed("没有需要删除的选项");
		}
		// 使用 Stream API 提取 deviceId 并组成 List<Long>
		List<Long> deviceIdList = duorouGreenhouseDeviceEntityList.stream()
				.map(DuorouGreenhouseDeviceEntity::getDeviceId)
				.toList();
//		删除的时候逻辑规定前端 只可以先选择大棚然后在解绑大棚里面的设备，所以尽管这里传入一个列表，实际都是一个大棚下的设备 大棚ID 相同 todo 先不实现参数的只管封装
		DuorouGreenhouseDeviceEntity duorouGreenhouseDevice = duorouGreenhouseDeviceEntityList.get(0);
		LambdaQueryWrapper<DuorouGreenhouseDeviceEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(DuorouGreenhouseDeviceEntity::getGreenhouseId,duorouGreenhouseDevice.getGreenhouseId());
		lambdaQueryWrapper.in(DuorouGreenhouseDeviceEntity::getDeviceId,deviceIdList);
		boolean b = duorouGreenhouseDeviceService.remove(lambdaQueryWrapper);
		//设置绑定状态
		LambdaUpdateWrapper<IotDeviceEntity> updateWrapper=new LambdaUpdateWrapper<>();
		updateWrapper.set(IotDeviceEntity::getDeviceBindStatus, IotDeviceStatusConstant.DEVICE_UN_BINDED_STATUS);
		updateWrapper.in(IotDeviceEntity::getId,deviceIdList);
		boolean update = iotDeviceService.update(updateWrapper);



		return R.ok((b && update));
    }


    /**
     * 导出excel 表格
     * @param duorouGreenhouseDevice 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('duorou_duorouGreenhouseDevice_export')" )
    public List<DuorouGreenhouseDeviceEntity> export(DuorouGreenhouseDeviceEntity duorouGreenhouseDevice,Long[] ids) {
        return duorouGreenhouseDeviceService.list(Wrappers.lambdaQuery(duorouGreenhouseDevice).in(ArrayUtil.isNotEmpty(ids), DuorouGreenhouseDeviceEntity::getId, ids));
    }
}